package com.qf.homework.aop;

import com.qf.homework.aop.anno.Retry;
import com.qf.homework.common.AppException;
import com.qf.homework.common.RetryException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Random;

/**
 * @author zehan
 * @date 2022/8/19 20:00
 */
@Component
@Aspect
@Order(Integer.MIN_VALUE)
public class RetryAspect {

    @Around("@annotation(com.qf.homework.aop.anno.Retry)")
    public Object needRetry(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Retry annotation = method.getAnnotation(Retry.class);

        int maxRetryNum = annotation.retryNum();
        int reSetNum = 0;

        do {
            try {
                Thread.sleep(new Random().nextInt(150));
                Object proceed = joinPoint.proceed();
                return proceed;
            }catch (RetryException retryException){
                reSetNum++;
                System.out.println("---正在重试----"+reSetNum+"-----");
            }
        }while (reSetNum<=maxRetryNum);
        throw new AppException("555","运气太不好了吧");
    }
}

